import axios from "axios";
import { showFailToast } from "vant";
import router from "../router";
export const service = axios.create({
  baseURL: "http://120.79.170.239:8082",
  timeout: 15000,
});
const MAX_RETRY_TIMES = 5; // 最大重试次数
async function fetchDataWithRetry(retryCount = 0) {
  try {
    await service.post("/wx/auth/login");
  } catch (error) {
    if (error.code === "ECONNABORTED" && retryCount < MAX_RETRY_TIMES) {
      console.log(`请求超时，正在尝试重新请求，重试次数：${retryCount + 1}`);
      await fetchDataWithRetry(retryCount + 1);
    } else if (retryCount >= MAX_RETRY_TIMES) {
      // 达到最大重试次数仍然失败，抛出错误
      showFailToast("请求超时，已达到最大重试次数，无法继续尝试。");
    }
  }
}
fetchDataWithRetry();
// 添加请求拦截器
service.interceptors.request.use(
  (config) => {
    // 添加请求头
    if (localStorage.getItem("token") != "") {
      config.headers["X-Litemall-Token"] = localStorage.getItem("token");
    }
    config.headers["Content-Type"] = "application/json";
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

//添加响应拦截器;
service.interceptors.response.use(
  (response) => {
    if (response.data.errmsg == "请登录") {
      showFailToast("请先登录");
      router.push("/login");
      return null;
    }
    return response;
  },
  (error) => {
    console.log(error);
    showFailToast("请求失败");
    return Promise.reject(error);
  }
);
